package durst.data.dao.impl;

import java.sql.SQLException;
import java.util.List;

import org.apache.log4j.Logger;

import com.j256.ormlite.dao.BaseDaoImpl;
import com.j256.ormlite.stmt.SelectArg;
import com.j256.ormlite.stmt.Where;
import com.j256.ormlite.support.ConnectionSource;

import durst.data.Account;
import durst.data.Event;
import durst.data.FileAccess;

public class FileAccessDao<T, ID> extends BaseDaoImpl<T, ID> {

	public FileAccessDao(Class<T> dataClass) throws SQLException {
		super(dataClass);
	}

	public FileAccessDao(ConnectionSource source, Class<T> clazz) throws SQLException {
		super(source, clazz);
	}

	@Override
	public int create(T data) {
		try {
			if (data instanceof FileAccess) {
				FileAccess access = (FileAccess) data;

				List<T> res = findByMetadata(access.getOwner(), access.getName(), access.getEvent());
				
				if (res.size() > 0) {
					access.setId(((FileAccess)res.get(0)).getId());
					return 0;
				}
			}
			return super.create(data);
		}
		catch (SQLException exc) {
			Logger.getLogger(FileAccessDao.class).error("FileAccess object creation failed!");
			return 0;
		}
	}
	
	public List<T> findByMetadata(Account owner, String filename, Event event) throws SQLException {
		SelectArg file = new SelectArg();
		file.setValue(filename);
		
		Where<T, ID> where = queryBuilder().where()
		.eq(FileAccess.OWNER_ID, owner.getId()).and()
		.eq(FileAccess.NAME, file);

		if (event != null)
			where.and().eq(FileAccess.EVENT_ID, event.getId());

		return where.query();
	}
	
	public T findProfile(Account owner) throws SQLException {
		List<T> res = queryBuilder().where().eq(FileAccess.OWNER_ID, owner.getId()).and().eq(FileAccess.EVENT_ID, null).query();
		
		assert(res.size() <= 1);
		
		return res.size() == 0 ? null : res.get(0);
	}
}
